package cn.xorange.commons.utils.validate;

import cn.xorange.commons.utils.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * @author : yangjian
 * date : 2021/11/16
 */
@Slf4j
public class MValidateHandle implements ConstraintValidator<MValidate,Object> {

    private MValidate mValidate;
    @Override
    public void initialize(MValidate constraintAnnotation) {
        this.mValidate = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(mValidate.message().isEmpty()){
            //禁用默认提示信息
            context.disableDefaultConstraintViolation();
            if(mValidate.nonNull() && Objects.isNull(value)){
                context.buildConstraintViolationWithTemplate("不能为空;").addConstraintViolation();
                return false;
            }else if(mValidate.min()!=0){
                if (value.toString().length() < mValidate.min()){
                    context.buildConstraintViolationWithTemplate(StringUtils.format("长度需大于{}个字符;",mValidate.min())).addConstraintViolation();
                    return false;
                }
            }else if(mValidate.max() !=0){
                if (value.toString().length()>mValidate.max()){
                    context.buildConstraintViolationWithTemplate(StringUtils.format("长度需小于{}个字符;",mValidate.max())).addConstraintViolation();
                    return false;
                }
            }
        }

        return true;
    }
}
